<template>
  <view class="register-container">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="back-btn" @click="goBack">
        <uni-icons type="left" size="24" color="#333"></uni-icons>
      </view>
      <text class="title">注册账号</text>
      <view class="placeholder"></view>
    </view>
    
    <!-- 注册表单 -->
    <view class="form-section">
      <view class="input-group">
        <view class="input-icon">
          <uni-icons type="person" size="20" color="#0086ff"></uni-icons>
        </view>
        <input 
          type="number" 
          v-model="phone" 
          placeholder="请输入手机号" 
          maxlength="11"
          class="input-item"
        />
      </view>
      
      <view class="input-group">
        <view class="input-icon">
          <uni-icons type="locked" size="20" color="#0086ff"></uni-icons>
        </view>
        <input 
          :type="showPassword ? 'text' : 'password'" 
          v-model="password" 
          placeholder="请输入密码（不少于6位）" 
          class="input-item"
        />
        <view class="password-toggle" @click="showPassword = !showPassword">
          <uni-icons :type="showPassword ? 'eye-filled' : 'eye-slash-filled'" size="20" color="#999"></uni-icons>
        </view>
      </view>
      
      <view class="input-group">
        <view class="input-icon">
          <uni-icons type="locked" size="20" color="#0086ff"></uni-icons>
        </view>
        <input 
          :type="showConfirmPassword ? 'text' : 'password'" 
          v-model="confirmPassword" 
          placeholder="确认密码" 
          class="input-item"
        />
        <view class="password-toggle" @click="showConfirmPassword = !showConfirmPassword">
          <uni-icons :type="showConfirmPassword ? 'eye-filled' : 'eye-slash-filled'" size="20" color="#999"></uni-icons>
        </view>
      </view>
      
      <view class="agreement">
        <checkbox :checked="agreed" @click="agreed = !agreed" color="#0086ff" style="transform:scale(0.7)" />
        <text class="agreement-text">我已阅读并同意<text class="link">《用户协议》</text>和<text class="link">《隐私政策》</text></text>
      </view>
      
      <button class="register-btn" :disabled="!agreed" :class="{'disabled': !agreed}" @click="handleRegister">注册</button>
      
      <view class="login-link" @click="goToLogin">
        已有账号，去登录
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      phone: '',
      password: '',
      confirmPassword: '',
      showPassword: false,
      showConfirmPassword: false,
      agreed: false
    }
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    
    // 验证手机号格式
    validatePhone() {
      // 保持原有逻辑
      const phoneReg = /^1[3-9]\d{9}$/;
      if (!this.phone) {
        uni.showToast({
          title: '请输入手机号',
          icon: 'none'
        });
        return false;
      }
      if (!phoneReg.test(this.phone)) {
        uni.showToast({
          title: '手机号格式不正确',
          icon: 'none'
        });
        return false;
      }
      return true;
    },
    
    // 验证密码
    validatePassword() {
      // 保持原有逻辑
      if (!this.password) {
        uni.showToast({
          title: '请输入密码',
          icon: 'none'
        });
        return false;
      }
      if (this.password.length < 6) {
        uni.showToast({
          title: '密码长度不能少于6位',
          icon: 'none'
        });
        return false;
      }
      return true;
    },
    
    // 验证确认密码
    validateConfirmPassword() {
      // 保持原有逻辑
      if (!this.confirmPassword) {
        uni.showToast({
          title: '请确认密码',
          icon: 'none'
        });
        return false;
      }
      if (this.password !== this.confirmPassword) {
        uni.showToast({
          title: '两次输入的密码不一致',
          icon: 'none'
        });
        return false;
      }
      return true;
    },
    
    // 处理注册
    handleRegister() {
      if (!this.agreed) {
        uni.showToast({
          title: '请先同意用户协议和隐私政策',
          icon: 'none'
        });
        return;
      }
      
      if (!this.validatePhone() || !this.validatePassword() || !this.validateConfirmPassword()) {
        return;
      }
      
      // 显示加载中
      uni.showLoading({
        title: '注册中...'
      });
      
      // 保持原有注册逻辑
      uni.request({
        url: 'http://localhost:3000/users',
        success: (res) => {
          if (res.statusCode === 200) {
            const users = res.data;
            const existingUser = users.find(u => u.phone === this.phone);
            
            if (existingUser) {
              uni.hideLoading();
              uni.showToast({
                title: '该手机号已被注册',
                icon: 'none'
              });
              return;
            }
            
            // 计算新用户的id
            let maxId = 0;
            users.forEach(user => {
              const userId = parseInt(user.id);
              if (!isNaN(userId) && userId > maxId) {
                maxId = userId;
              }
            });
            const newId = (maxId + 1).toString();
            
            // 手机号未被注册，继续注册流程
            uni.request({
              url: 'http://localhost:3000/users',
              method: 'POST',
              data: {
                id: newId,
                phone: this.phone,
                password: this.password,
                username: '用户' + this.phone.substring(7)
              },
              header: {
                'content-type': 'application/json'
              },
              success: (addRes) => {
                uni.hideLoading();
                
                if (addRes.statusCode === 201) {
                  uni.showToast({
                    title: '注册成功',
                    icon: 'success',
                    duration: 2000
                  });
                  
                  // 注册成功后跳转到登录页面
                  setTimeout(() => {
                    uni.navigateTo({
                      url: '/pages/login/login'
                    });
                  }, 2000);
                } else {
                  uni.showToast({
                    title: '注册失败，请稍后再试',
                    icon: 'none'
                  });
                }
              },
              fail: () => {
                uni.hideLoading();
                uni.showToast({
                  title: '网络错误，请稍后再试',
                  icon: 'none'
                });
              }
            });
          } else {
            uni.hideLoading();
            uni.showToast({
              title: '网络错误，请稍后再试',
              icon: 'none'
            });
          }
        },
        fail: () => {
          uni.hideLoading();
          uni.showToast({
            title: '网络错误，请稍后再试',
            icon: 'none'
          });
        }
      });
    },
    
    // 跳转到登录页面
    goToLogin() {
      uni.navigateTo({
        url: '/pages/login/login'
      });
    }
  }
}
</script>

<style lang="scss">
.register-container {
  min-height: 100vh;
  background-color: #ffffff;
  padding: 0 40rpx;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 40rpx 0;
  
  .back-btn {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
  }
  
  .title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
  }
  
  .placeholder {
    width: 60rpx;
  }
}

.form-section {
  margin-top: 40rpx;
  
  .input-group {
    display: flex;
    align-items: center;
    margin-bottom: 40rpx;
    padding: 10rpx 30rpx;
    transition: all 0.3s;
    position: relative;
    border: 1px solid #e0e0e0;
    border-radius: 8rpx;
    height: 90rpx;
    
    .input-icon {
      margin-right: 20rpx;
      display: flex;
      align-items: center;
    }
    
    .input-item {
      flex: 1;
      height: 90rpx;
      font-size: 32rpx;
      color: #333;
      border: none;
      background: transparent;
      
      &::placeholder {
        color: #999;
      }
    }
    
    .password-toggle {
      padding: 10rpx;
    }
  }
  
  .agreement {
    display: flex;
    align-items: center;
    margin: 30rpx 0;
    
    .agreement-text {
      font-size: 26rpx;
      color: #666;
      
      .link {
        color: #0086ff;
      }
    }
  }
  
  .register-btn {
    background: linear-gradient(to right, #0086ff, #00b0ff);
    color: #fff;
    height: 90rpx;
    line-height: 90rpx;
    border-radius: 45rpx;
    font-size: 32rpx;
    margin-top: 60rpx;
    box-shadow: 0 10rpx 20rpx rgba(0, 134, 255, 0.2);
    transition: all 0.2s;
    
    &:active {
      transform: scale(0.98);
      box-shadow: 0 5rpx 10rpx rgba(0, 134, 255, 0.2);
    }
    
    &.disabled {
      background: linear-gradient(to right, #cccccc, #dddddd);
      box-shadow: none;
    }
  }
  
  .login-link {
    text-align: center;
    margin-top: 40rpx;
    font-size: 28rpx;
    color: #0086ff;
    padding: 20rpx 0;
  }
}
</style>